﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace QW.Core
{
    /*
     标准的Snowflake算法,假如从2010年开始 可以使用到2079年
     默认计算规则
     第1位为0表示正数
     第2-42位为毫秒级时间戳
     第43-52位为工作机ID 最多1024台机器
     第53-64位为序列号
     */
    /// <summary>
    /// 雪花Id
    /// </summary>
    public struct SnowflakeId : IEquatable<SnowflakeId>, IComparable, IComparable<long>, IConvertible, IEquatable<long>, IFormattable
    {
        #region 静态参数
        // 各字段位移量
        private const ushort TimestampBits = 41;
        private const ushort MachineIdBits = 10;
        private const ushort SequenceBits = 12;
        private const long MaxMachineId = (1L << MachineIdBits) - 1;
        private const long MaxSequence = (1L << SequenceBits) - 1;
        private const ushort MachineIdShift = SequenceBits;
        private const ushort TimestampShift = SequenceBits + MachineIdBits;
        private const long TimestampMask = (1L << TimestampBits) - 1; // 时间戳字段掩码
        private static long _lastTimestamp = -1L;
        private static long _sequence = 0L;
        /// <summary>
        /// 当前机器编码
        /// </summary>
        private static ushort currentMachineId = 1;
        /// <summary>
        /// 当前机器编码
        /// </summary>
        public static ushort CurrentMachineId => currentMachineId;
        /// <summary>
        /// 当前基准时间戳
        /// </summary>
        public static long currentTwepoch = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero).ToUnixTimeMilliseconds();
        /// <summary>
        /// 当前基准时间戳,默认2020-01-01
        /// </summary>
        public static long CurrentTwepoch => currentTwepoch;
        #endregion

        #region 静态方法
        private static object _lock = new object();
        /// <summary>
        /// 初始
        /// </summary>
        /// <param name="machineId">机器编码</param>
        /// <param name="twepoch">基准时间戳,0表示按默认(2020-01-01)</param>
        public static void Init(ushort machineId, long twepoch = 0)
        {
            lock (_lock)
            {
                if (machineId < 0 || machineId > MaxMachineId)
                    throw new ArgumentException($"machineId 必须在 0 到 {MaxMachineId} 之间");
                currentMachineId = machineId;
                if (twepoch > 0)
                {
                    currentTwepoch = twepoch;
                }
            }
        }
        private const long ClockBackwardsThreshold = 5; // 允许5ms内的回拨
        /// <summary>
        /// 生成雪花ID
        /// </summary>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static long NextId()
        {
            lock (_lock)
            {
                long currentTimestamp = GetCurrentTimestamp();

                // 处理时钟回拨（给服务器留5ms误差）
                if (currentTimestamp < _lastTimestamp)
                {
                    long diff = _lastTimestamp - currentTimestamp;
                    if (diff <= ClockBackwardsThreshold)
                    {
                        // 等待时钟追上
                        Thread.Sleep((int)diff);
                        currentTimestamp = GetCurrentTimestamp();
                    }
                    else
                    {
                        throw new InvalidOperationException($"时钟回拨过大（{diff}ms），无法生成ID");
                    }
                }

                // 同一毫秒内，序列号自增
                if (currentTimestamp == _lastTimestamp)
                {
                    _sequence = (_sequence + 1) & MaxSequence;
                    // 序列号用尽，等待下一毫秒
                    if (_sequence == 0)
                        currentTimestamp = WaitNextMillisecond(_lastTimestamp);
                }
                else
                {
                    _sequence = 0;
                }

                _lastTimestamp = currentTimestamp;

                // 拼接ID：时间戳 << 位移 + 机器ID << 位移 + 序列号
                return ((currentTimestamp - currentTwepoch) << TimestampShift)
                       | (CurrentMachineId << MachineIdShift)
                       | _sequence;
            }
        }

        /// <summary>
        /// 获取当前毫秒级时间戳
        /// </summary>
        /// <returns></returns>
        private static long GetCurrentTimestamp()
        {
            return DateTimeOffset.Now.ToUnixTimeMilliseconds();
        }

        /// <summary>
        /// 等待下一毫秒
        /// </summary>
        /// <param name="lastTimestamp"></param>
        /// <returns></returns>
        private static long WaitNextMillisecond(long lastTimestamp)
        {
            long timestamp = GetCurrentTimestamp();
            while (timestamp <= lastTimestamp)
                timestamp = GetCurrentTimestamp();
            return timestamp;
        }
        #endregion

        #region 属性
        /// <summary>
        /// 值本体
        /// </summary>
        private long _snowflakeId;
        /// <summary>
        /// 基准时间戳
        /// </summary>
        private long twepoch;

        /// <summary>
        /// 基准时间戳
        /// </summary>
        public long Twepoch => twepoch;
        /// <summary>
        /// 值
        /// </summary>
        public long Value => _snowflakeId;
        /// <summary>
        /// 时间戳原值
        /// </summary>
        public long TimeStamp => (_snowflakeId >> TimestampShift) & TimestampMask;
        /// <summary>
        /// 时间
        /// </summary>
        public DateTime DateTime
        {
            get
            {
                long ts = TimeStamp + twepoch;
                var utct = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ts);
                return utct.ToLocalTime();
            }
        }
        /// <summary>
        /// 机器码
        /// </summary>
        public ushort MachineId => (ushort)((_snowflakeId >> MachineIdShift) & MaxMachineId);
        /// <summary>
        /// 序列
        /// </summary>
        public ushort Sequence => (ushort)(_snowflakeId & MaxSequence);

        #endregion

        #region ctor
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="snowflakeId">雪花Id</param>
        public SnowflakeId(long snowflakeId)
        {
            this._snowflakeId = snowflakeId;
            this.twepoch = SnowflakeId.CurrentTwepoch;
        }
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="snowflakeId">雪花Id</param>
        /// <param name="twepoch">基准时间戳</param>
        public SnowflakeId(long snowflakeId, long twepoch)
        {
            this._snowflakeId = snowflakeId;
            this.twepoch = twepoch;
        }
        #endregion

        #region 适配
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return _snowflakeId.ToString();
        }

        public override bool Equals(object obj)
        {
            if (obj is SnowflakeId snowflake)
            {
                return snowflake.Equals(this);
            }
            if (obj is long num)
            {
                return this._snowflakeId == num;
            }
            return base.Equals(obj);
        }

        public bool Equals(SnowflakeId other)
        {
            return other.Value == _snowflakeId;
        }

        public static bool operator ==(SnowflakeId d1, SnowflakeId d2)
        {
            return d1.Equals(d2);
        }

        public static bool operator !=(SnowflakeId d1, SnowflakeId d2)
        {
            return !d1.Equals(d2);
        }

        public static implicit operator SnowflakeId(long value)
        {
            return new SnowflakeId(value);
        }

        public static implicit operator long(SnowflakeId value)
        {
            return value.Value;
        }

        public override int GetHashCode()
        {
            return _snowflakeId.GetHashCode();
        }

        public int CompareTo(object obj)
        {
            return _snowflakeId.CompareTo(obj);
        }

        public int CompareTo(long other)
        {
            return _snowflakeId.CompareTo(other);
        }

        TypeCode IConvertible.GetTypeCode()
        {
            return ((IConvertible)_snowflakeId).GetTypeCode();
        }

        bool IConvertible.ToBoolean(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToBoolean(provider);
        }

        byte IConvertible.ToByte(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToByte(provider);
        }

        char IConvertible.ToChar(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToChar(provider);
        }

        DateTime IConvertible.ToDateTime(IFormatProvider provider)
        {
            return DateTime;
        }

        decimal IConvertible.ToDecimal(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToDecimal(provider);
        }

        double IConvertible.ToDouble(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToDouble(provider);
        }

        short IConvertible.ToInt16(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToInt16(provider);
        }

        int IConvertible.ToInt32(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToInt32(provider);
        }

        long IConvertible.ToInt64(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToInt64(provider);
        }

        sbyte IConvertible.ToSByte(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToSByte(provider);
        }

        float IConvertible.ToSingle(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToSingle(provider);
        }

        string IConvertible.ToString(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToString(provider);
        }

        object IConvertible.ToType(Type conversionType, IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToType(conversionType, provider);
        }

        ushort IConvertible.ToUInt16(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToUInt16(provider);
        }

        uint IConvertible.ToUInt32(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToUInt32(provider);
        }

        ulong IConvertible.ToUInt64(IFormatProvider provider)
        {
            return ((IConvertible)_snowflakeId).ToUInt64(provider);
        }

        public bool Equals(long other)
        {
            return _snowflakeId.Equals(other);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            return ((IFormattable)_snowflakeId).ToString(format, formatProvider);
        }

        public string ToString(string format)
        {
            return _snowflakeId.ToString(format);
        }

        public static SnowflakeId Parse(string s)
        {
            return new SnowflakeId(long.Parse(s));
        }

        public static bool TryParse(string s, out SnowflakeId result)
        {
            if (long.TryParse(s, out long id))
            {
                result = new SnowflakeId(id);
                return true;
            }
            result = default;
            return false;
        }
        #endregion
    }
}
